package ms.unicorn.diagram.providers;

import java.util.Hashtable;

import org.eclipse.gmf.runtime.common.ui.services.action.global.AbstractGlobalActionHandlerProvider;
import org.eclipse.gmf.runtime.common.ui.services.action.global.IGlobalActionHandler;
import org.eclipse.gmf.runtime.common.ui.services.action.global.IGlobalActionHandlerContext;
import org.eclipse.gmf.runtime.diagram.ui.render.internal.providers.ImageSupportGlobalActionHandler;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWorkbenchPart;

public class UnicornGlobalAcctionHandlerProvider extends AbstractGlobalActionHandlerProvider {

	/**
	 * List for handlers.
	 */
	private Hashtable handlerList = new Hashtable();

	/**
	 * Creates a new instance.
	 */
	public UnicornGlobalAcctionHandlerProvider() {
		super();
	}

	/**
	 * Returns a global action handler that supports global image operations
	 * (cut, copy, and paste).
	 */
	public IGlobalActionHandler getGlobalActionHandler(
			final IGlobalActionHandlerContext context) {
		/* Create the handler */
		 
		if (!getHandlerList().containsKey(context.getActivePart())) {
				getHandlerList().put(context.getActivePart(),
				new UnicornClipboardSupportGlobalActionHandler());	 
		 
			/* Register as a part listener so that the cache can be cleared when
			* the part is disposed
			*/
		 
			context.getActivePart().getSite().getPage().addPartListener( new IPartListener() {
				private IWorkbenchPart localPart = context.getActivePart();
				
				public void partActivated(IWorkbenchPart part) { }
	 
				public void partBroughtToTop(IWorkbenchPart part) {}
	 
				public void partClosed(IWorkbenchPart part) {
					/* Remove the cache associated with the part */
					if (part != null && part == localPart && getHandlerList().containsKey(part)) {
						getHandlerList().remove(part);
						localPart.getSite().getPage().removePartListener(this);
						localPart = null; 
					}
				}
			 
				public void partDeactivated(IWorkbenchPart part) { }
			 
				public void partOpened(IWorkbenchPart part) {}
				});
		}
		return (UnicornClipboardSupportGlobalActionHandler) getHandlerList().get( context.getActivePart());
	}

	/**
	 * Returns the handlerList.
	 * 
	 * @return Hashtable
	 */
	private Hashtable getHandlerList() {
		return handlerList;
	}

}
